import { login, logout, getInfo } from "@/api/user";
import { getToken, setToken, removeToken } from "@/utils/auth";
import { resetRouter } from "@/router";
import messageApi from "../../api/admin.js";
const getDefaultState = () => {
  return {
    token: getToken(),
    name: "",
    avatar:
      "https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif",
    // userId: ""
  };
};

const state = getDefaultState();

const mutations = {
  RESET_STATE: state => {
    Object.assign(state, getDefaultState());
  },
  SET_TOKEN: (state, token) => {
    state.token = token;
  },
  SET_NAME: (state, name) => {
    state.name = name;
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar;
  },
  // SET_ID: (state, id) => {
  //   state.userId = id
  // },
};

const actions = {
  // 注册
  async regActions(context, payload) {
    let obj = {
      username: payload.username,
      password: payload.password,
      name: payload.name,
      age: payload.age,
      gender: payload.gender,
      phone: payload.phone,
      position: "门店管理员", // 职位(门店管理员)
      status: "申请中" // 状态(申请中)
    };
    return await messageApi.regAdmin(obj).then(res => {
      return res; // 返回状态值判断，显示用户是否已经注册
    });
  },
  // 登录
  login({ commit }, userInfo) {
    const { username, password } = userInfo;
    return new Promise((resolve, reject) => {
      login({ username: username.trim(), password: password })
        .then(response => {
          // 平台管理员和门店管理员登录获取的信息不一样, position 获取到了账号的角色信息
          // (平台管理员 0 / 门店管理员 1 )
          const { data, token } = response;
          setToken(data.position);
          if (data.position == "门店管理员") {
            localStorage.setItem("shopAdminId", data._id); // 存储门店管理员 ID
          }
          localStorage.setItem("loginToken", token); // 本地存储后台生成的 token
          localStorage.setItem("household_token", data.position); // 将 token 存储在本地
          resolve(response.data);
        })
        .catch(error => {
          reject(error);
        });
    });
  },

  // get user info
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfo(state.token)
        .then(response => {
          const { data } = response;
          if (!data) {
            return reject("Verification failed, please Login again.");
          }
          const { name, avatar, userId } = data;
          commit("SET_NAME", name);
          commit("SET_AVATAR", avatar);
          // commit('SET_ID', userId)
          resolve(data);
        })
        .catch(error => {
          reject(error);
        });
    });
  },
  // user logout
  logout() {
    // 删除指定本地存储
    localStorage.removeItem("household_token");
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      removeToken(); // must remove  token  first
      commit("RESET_STATE");
      resolve();
    });
  }
};

export default {
  namespaced: true,
  state,
  mutations,
  actions
};
